<?php

require_once("root.php");
require_once($ROOT . "util/CodeLookupUtil.php");
require_once($ROOT . "util/HtmlUtil.php");
require_once($ROOT . "util/UserUtil.php");
require_once($ROOT . "util/Cacher.php");

function get_ajax_contents($filename, $pageValue, $args=array()) {
   $user = UserUtil::getCurrentUser();
   $userId = $user->id;
   ob_start();
   include $filename;
   $contents = ob_get_contents();
   ob_end_clean();

   $contents = str_ireplace("\n", "", $contents);
   return $contents;
}


// Some useful global functions
function safeEscapeStr($string) {
	 if (get_magic_quotes_gpc()) {
	   return $string;
	 } else {
	   return mysql_real_escape_string($string);
	 }
}

function tableDropdown($name, $selectedValue, $optionObjects, $label, $value="id")
{
	$html = "";
	$html .= "<select name=\"$name\">\n";
	$html .= "\t<option value=\"\">---</option>\n";
    foreach ($optionObjects as $object)
    {
    	$finalLabel = $label;
    	$words = split("[ ,\(\)\\]+", trim($label));
    	foreach ($words as $word)
    	{
    		$labelValue = $object->$word;
    		$finalLabel = str_replace($word, $labelValue, $finalLabel);
    	}
    	$html .=  "\t<option value=\"" . $object->$value . "\"";
    	if ($selectedValue == $object->$value) $html .=  " selected";
    	$html .=  ">$finalLabel</option>\n";
    }
    $html .=  "</select>";

    return $html;
}

function dropdown($name, $selectedValue=null, $table=null)
{
	if ($table == null)
	{
		$codeLookupOptions = CodeLookupUtil::getCodes($name);
	}
	else
	{
		$codeLookupOptions = CodeLookupUtil::getCodes($table);
	}
	$html = "";
	$html .= "<select name=\"$name\">\n";
	$html .= "\t<option value=\"\">---</option>\n";
    foreach ($codeLookupOptions as $codeLookup)
    {
    	$html .=  "\t<option value=\"$codeLookup->code_key\"";
    	if ($selectedValue == $codeLookup->code_key) $html .=  " selected";
    	$html .=  ">$codeLookup->value</option>\n";
    }
    $html .=  "</select>";

    return $html;
}

function displayErrors($errors)
{
	$html = "";
	if (count($errors) > 0)
	{
		$html .= "<div style=\"background-color:red;color:white;\">";
		foreach ($errors as $error)
		{
			$html .= $error . "<br/>";
		}
		$html .= "</div>";
	}

	return $html;
}

function displayMessages($messages)
{
	$html = "";
	if (count($messages) > 0)
	{
		$html .= "<div style=\"background-color:blue;color:white;\">";
		foreach ($messages as $message)
		{
			$html .= $message . "<br/>";
		}
		$html .= "</div>";
	}

	return $html;
}

?>
